<?php

namespace addons\wwh\controller;

use think\Db;
use think\Request;
use addons\wwh\model\Column as ColumnModel;

class Archives extends Base
{
    public function index()
    {
        //测试是否会产生website
        $diyname = $this->request->param('diyname/s');
        $id = $this->request->param('id/d');

        // 验证参数
        if (empty($diyname) || empty($id)) {
            $this->error('参数错误！');
        }

        // 获取当前活动栏目
        $navCur = Db::name('wwh_column')->where('diyname', $diyname)->where('lang', $this->lang)->find();
        if (!$navCur) {
            $this->error('栏目不属于当前语言或未知栏目！');
        }

        // 获取栏目详情及关联信息
        $archives = Db::name('wwh_archives')
            ->alias('a')
            ->join('wwh_column c', 'c.id = a.column_id')
            ->field('a.*,c.parent_id,c.diyname,c.name')
            ->where('a.status', '1')
            ->where('a.id', $id)
            ->find();

        if (!$archives) {
            $this->error('内容未审核或不存在！');
        }

        // 获取顶级栏目
        $topId = ColumnModel::getTopColumn($navCur);

        // 处理轮播图
        $archives['lunbo'] = !empty($archives['images']) ? explode(',', $archives['images']) : [];

        // 查询相邻文章
        $queryParams = [
            'lang' => $this->lang,
            'status' => '1',
            'column_id' => $archives['column_id']
        ];

        $getAdjacent = function($type, $compare, $order) use ($id, $queryParams) {
            return Db::name('wwh_archives')
                ->where($queryParams)
                ->where('classify', $type)
                ->where('id', $compare, $id)
                ->order('id', $order)
                ->limit(1)
                ->find();
        };

        // 使用数组存储相邻文章
        $adjacentArticles = [
            'cfront' => $getAdjacent('cases', '>', 'asc'),
            'cafter' => $getAdjacent('cases', '<', 'desc'),
            'nfront' => $getAdjacent('news', '>', 'asc'),
            'nafter' => $getAdjacent('news', '<', 'desc')
        ];

        // 更新浏览数
        Db::name('wwh_archives')
            ->where('id', $id)
            ->update([
                'views' => Db::raw('views+1'),
                'updatetime' => time()
            ]);

        // 处理模板路径
        $template = preg_replace('/\.html$/', '', $archives['tpl']);

        // 获取当前语言下所有栏目ID
        $columnIds = Db::name('wwh_column')->where('lang', $this->lang)->column('id');

        // 判断当前内容的栏目ID是否属于当前语言
        if (!in_array($archives['column_id'], $columnIds)) {
            $this->error('栏目不属于当前语言或不存在！');
        }

        // 分配所有模板变量
        $this->view->assign(array_merge([
            'navCur' => $navCur,
            'top' => $topId,
            'archives' => $archives,
            'template' => $template
        ], $adjacentArticles));

        return $this->view->fetch('/' . $template);
    }
}
